//
//  PhotoCollection_Board.m
//  dingding
//
//  Created by LHL on 14/12/15.
//  Copyright (c) 2014年 com.gordon. All rights reserved.
//

#import "PhotoCollection_Board.h"
#import "PhotoCollectionViewCell.h"
#import "dynamicsVC.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "collectionFooter.h"
#import "Common.h"
#import "AppBoard_iPhone.h"
@interface PhotoCollection_Board ()

@end

@implementation PhotoCollection_Board{
    NSMutableArray *data;
    NSMutableArray *photoData;
    UIButton *preview;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    data = [[NSMutableArray alloc]init];
    photoData = [[NSMutableArray alloc]init];
    self.assets = [[NSMutableArray alloc]init];
    self.collectionview.backgroundColor = [UIColor whiteColor];
//    [self.collectionview registerClass:[collectionFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"myfooter"];
    self.title = [self.model valueForProperty:ALAssetsGroupPropertyName];
    self.navigationBarRight = @"取消";
    self.navigationBarLeft = [UIImage imageNamed:@"back.png"];
    self.collectionview.contentSize = CGSizeMake(0, 5+self.model.numberOfAssets *75+40);
    UIView *sure = [[UIView alloc]initWithFrame:CGRectMake(0, self.frame.size.height-64-40, self.frame.size.width, 40)];
    [sure setBackgroundImage:[UIImage imageNamed:@"photo-foot"]];
    [self.view addSubview:sure];
    [self reloadDatas];
    preview = [UIButton buttonWithType:UIButtonTypeCustom];
    [preview setTitle:@"确定" forState:0];
    [preview addTarget:self action:@selector(loading) forControlEvents:UIControlEventTouchUpInside];
    [preview setTitleColor:[UIColor whiteColor] forState:0];
    [preview.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [preview setBackgroundImage:[UIImage imageNamed:@"photobutton-enable.png"] forState:0];
    [preview setBackgroundImage:[UIImage imageNamed:@"photobutton-disenable.png"] forState:UIControlStateDisabled];
    preview.enabled = NO;
    preview.frame = CGRectMake(self.frame.size.width-80, 5, 60, 30);
    [sure addSubview:preview];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)reloadDatas{
    [self.model enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if(result) {
            [self.assets addObject:result];
        }
    }];
    [self.collectionview reloadData];
}

-(void)loading{
    [self presentLoadingTips:@"处理中"];
    [self performSelector:@selector(confirm) withObject:nil afterDelay:0.1];
}

-(void)confirm{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dir = [path stringByAppendingPathComponent:@"SandBoxphoto"];
    for (int i = 0 ; i < data.count; i++) {
        NSInteger index = [data[i] integerValue];
        ALAsset *result = [self.assets objectAtIndex:index];
        UIImage *img = [UIImage imageWithCGImage:[[result defaultRepresentation]fullScreenImage]];
        NSInteger imglength = [UIImageJPEGRepresentation(img, 1.0) length];
        NSData *small = UIImageJPEGRepresentation(img, (imglength %10)/imglength);
        NSString *filename = [[result defaultRepresentation]filename];
        NSString * imagePath = [dir stringByAppendingPathComponent:filename];
        if ([small writeToFile:imagePath atomically:YES]) {
            NSLog(@"写入成功");
            [photoData addObject:imagePath];
        }else{
            NSLog(@"写入失败");
        }
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"photo" object:photoData];
    [self popFunc];
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
    [self popFunc];
}
-(void)getpopBlock:(popBlock)block{
    self.block = [block copy];
}

-(void)popFunc{
    [self dismissTips];
    if (self.block) {
        [self.navigationController popViewControllerAnimated:NO];
        self.block();
    }
//    dynamicsVC *dyvc;
//    for (UIViewController *vc  in self.navigationController.viewControllers) {
//        if ([vc isKindOfClass:[dynamicsVC class]]) {
//            dyvc = (dynamicsVC *)vc;
//            break;
//        }
//    }
//    [self.navigationController popToViewController:dyvc animated:NO];
//    [UIView commitAnimations];
}



ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

//ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
//{
//    [self.navigationController popViewControllerAnimated:NO];
//}

#pragma mark <UICollectionViewDataSource>

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionFooter){
        collectionFooter *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        if (footerview == nil) {
            footerview = [[collectionFooter alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 48)];
        }
        footerview.titlelabel.text = [NSString stringWithFormat:@"共%d张图片",self.model.numberOfAssets];
        reusableview = footerview;
    }
    return reusableview;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(self.view.bounds.size.width, 48);
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.assets.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoCollectionViewCell *cell = (PhotoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"photoCell" forIndexPath:indexPath];
    ALAsset *asset = self.assets[indexPath.row];
    cell.image.image = [UIImage imageWithCGImage:[asset thumbnail]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BOOL haveadd = YES;
    for (int i = 0; i < data.count; i++) {
        if ([data[i] isEqualToString:[NSString stringWithFormat:@"%ld",(long)indexPath.row]]) {
            [data removeObjectAtIndex:i];
            haveadd = NO;
            break;
        }
    }
    if (haveadd) {
        if (data.count == 9) {
            return;
        }
        [data addObject:[NSString stringWithFormat:@"%ld",(long)indexPath.row]];
    }
    if (data.count == 0) {
        [preview setBackgroundColor:[UIColor grayColor]];
        preview.enabled = NO;
    }else{
        preview.enabled = YES;
        [preview setBackgroundColor:RGB(243, 65, 65)];
    }
    
    PhotoCollectionViewCell *cell = (PhotoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.status.hidden = !cell.status.hidden;
}


@end
